<template>
  <div class="container">
    <!-- 移动端菜单切换按钮 -->
    <div class="mobile-menu-toggle md:hidden">
      <el-button 
        type="primary" 
        circle 
        size="small"
        class="menu-toggle-btn"
        @click="toggleMobileMenu"
      >
        <el-icon><Menu /></el-icon>
      </el-button>
    </div>

    <!-- 头部：包含标题、添加/导出按钮 -->
    <div class="flex flex-wrap items-center justify-between mb-6 gap-3">
      <!-- 标题 -->
      <div>
        <h1 class="page-title text-2xl font-bold">驾驶员管理</h1>
        <p class="text-gray-500">管理所有驾驶员基本信息、证件和相关记录</p>
      </div>
      <!-- 添加/导出按钮 -->
      <div class="flex gap-2">
        <el-button type="primary" @click="openDialog()" class="btn-with-icon">
          <el-icon class="mr-1"><Plus /></el-icon>添加驾驶员
        </el-button>
        <el-button type="success" @click="exportData" class="btn-with-icon">
          <el-icon class="mr-1"><Download /></el-icon>导出数据
        </el-button>
      </div>
    </div>

    <!-- 搜索区域框 -->
    <el-card shadow="hover" class="mb-6 card-with-hover">
      <div class="search-container">
        <!-- 姓名搜索 -->
        <div class="search-item">
          <el-input
            v-model="searchForm.name"
            placeholder="请输入驾驶员姓名"
            class="search-input"
            clearable
          >
            <template #prefix>
              <el-icon class="search-icon"><User /></el-icon>
            </template>
          </el-input>
        </div>
        
        <!-- 手机号搜索 -->
        <div class="search-item">
          <el-input
            v-model="searchForm.phone"
            placeholder="请输入手机号"
            class="search-input"
            clearable
          >
            <template #prefix>
              <el-icon class="search-icon"><Phone /></el-icon>
            </template>
          </el-input>
        </div>
        
        <!-- 状态搜索 -->
        <div class="search-item">
          <el-select
            v-model="searchForm.status"
            placeholder="请选择状态"
            class="search-input"
            clearable
          >
            <el-option
              v-for="(label, value) in statusOptions"
              :key="value"
              :label="label"
              :value="value"
            />
          </el-select>
        </div>
        
        <!-- 操作按钮 -->
        <div class="search-actions">
          <el-button type="primary" @click="handleSearch" class="search-btn">
            <el-icon class="mr-1"><Search /></el-icon>查询
          </el-button>
          
          <el-button @click="resetSearch" class="reset-btn" type="info" plain>
            <el-icon class="mr-1"><Refresh /></el-icon>重置
          </el-button>
        </div>
      </div>
    </el-card>

    <!-- 数据表格 -->
    <el-card shadow="hover" class="overflow-hidden card-with-hover">
      <el-table
        v-loading="loading"
        :data="filteredDrivers"
        border
        stripe
        style="width: 100%"
        :header-cell-class-name="'bg-gray-100 dark:bg-gray-700'"
        class="custom-table"
        fit
        @sort-change="handleSortChange"
      >
        <!-- 固定列 -->
        <el-table-column prop="id" label="ID" width="80" align="center" sortable="custom" fixed="left" />
        <el-table-column prop="name" label="姓名" min-width="100" sortable="custom" fixed="left" />
        
        <!-- 中等屏幕及以上显示的列 -->
        <el-table-column prop="gender" label="性别" width="80" class-name="hide-on-mobile" sortable="custom" />
        <el-table-column prop="phone" label="手机号" min-width="120" class-name="hide-on-mobile" />
        <el-table-column prop="department" label="部门" min-width="120" class-name="hide-on-mobile" sortable="custom" />
        <el-table-column prop="age" label="年龄" width="80" class-name="hide-on-mobile" sortable="custom" />
        <el-table-column prop="licenseNumber" label="驾驶证号" min-width="180" class-name="hide-on-mobile" sortable="custom" />
        <el-table-column prop="status" label="状态" min-width="100" sortable="custom" class-name="hide-on-mobile">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">{{ getStatusLabel(row.status) }}</el-tag>
          </template>
        </el-table-column>
        
        <!-- 操作列 -->
        <el-table-column label="操作" width="120" fixed="right">
          <template #default="scope">
            <div class="action-buttons">
              <el-button 
                type="primary" 
                size="small"
                circle
                @click="handleEdit(scope.row)"
                class="edit-btn"
              >
                <el-icon><Edit /></el-icon>
              </el-button>
              <el-button 
                type="danger" 
                size="small"
                circle
                @click="handleDelete(scope.row)"
                class="delete-btn"
              >
                <el-icon><Delete /></el-icon>
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页器 -->
      <div class="pagination-container mt-4 flex justify-center">
        <el-pagination
          :current-page="currentPage"
          :page-size="pageSize"
          :page-sizes="DEFAULT_PAGE_SIZES"
          :total="totalDrivers"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          background
          class="custom-pagination"
        />
      </div>
    </el-card>

    <!-- 添加/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="isEdit ? '编辑驾驶员' : '添加驾驶员'"
      width="500px"
      destroy-on-close
      class="custom-dialog"
    >
      <el-form
        ref="formRef"
        :model="driverForm"
        :rules="rules"
        label-width="100px"
        label-position="right"
        class="form-container"
      >
        <el-form-item label="姓名" prop="name">
          <el-input v-model="driverForm.name" placeholder="请输入姓名" />
        </el-form-item>
        <el-form-item label="性别" prop="gender">
          <el-radio-group v-model="driverForm.gender">
            <el-radio label="男">男</el-radio>
            <el-radio label="女">女</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="出生日期" prop="birthDate">
          <el-date-picker
            v-model="driverForm.birthDate"
            type="date"
            placeholder="选择出生日期"
            style="width: 100%"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="driverForm.phone" placeholder="请输入手机号" />
        </el-form-item>
        <el-form-item label="身份证号" prop="idCardNumber">
          <el-input v-model="driverForm.idCardNumber" placeholder="请输入身份证号" />
        </el-form-item>
        <el-form-item label="部门" prop="department">
          <el-select v-model="driverForm.department" placeholder="请选择部门" style="width: 100%" filterable>
            <el-option
              v-for="dept in departmentOptions"
              :key="dept"
              :label="dept"
              :value="dept"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="驾驶证号" prop="licenseNumber">
          <el-input v-model="driverForm.licenseNumber" placeholder="请输入驾驶证号" />
        </el-form-item>
        <el-form-item label="驾驶证类型" prop="licenseType">
          <el-select v-model="driverForm.licenseType" placeholder="请选择驾驶证类型" style="width: 100%">
            <el-option
              v-for="type in licenseTypes"
              :key="type"
              :label="type"
              :value="type"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="驾驶证到期日" prop="licenseExpiryDate">
          <el-date-picker
            v-model="driverForm.licenseExpiryDate"
            type="date"
            placeholder="选择驾驶证到期日"
            style="width: 100%"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="driverForm.status" placeholder="请选择状态" style="width: 100%">
            <el-option
              v-for="(label, value) in statusOptions"
              :key="value"
              :label="label"
              :value="value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="入职日期" prop="joinDate">
          <el-date-picker
            v-model="driverForm.joinDate"
            type="date"
            placeholder="选择入职日期"
            style="width: 100%"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="driverForm.remark" type="textarea" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Download, Search, Refresh, Edit, Delete, Menu, User, Phone } from '@element-plus/icons-vue'
import { driverApi } from '@/api'

export default {
  name: 'Drivers',
  setup() {
    // 常量
    const DEFAULT_PAGE_SIZES = [10, 20, 50, 100]
    const departmentOptions = ['综合部', '运营部', '后勤部', '安保部', '人事部', '财务部']
    const statusOptions = {
      '1': '在职',
      '2': '请假',
      '3': '停职',
      '4': '离职'
    }

    // 表单相关
    const formRef = ref(null)
    const dialogVisible = ref(false)
    const isEdit = ref(false)
    const driverForm = reactive({
      id: null,
      name: '',
      gender: '男',
      birthDate: '',
      phone: '',
      idCardNumber: '',
      department: '',
      licenseNumber: '',
      licenseType: 'C1',
      licenseExpiryDate: '',
      status: '1',
      joinDate: '',
      remark: ''
    })

    // 搜索相关
    const searchForm = reactive({
      name: '',
      phone: '',
      status: ''
    })

    // 表格相关
    const loading = ref(false)
    const drivers = ref([])
    const currentPage = ref(1)
    const pageSize = ref(10)
    const totalDrivers = ref(0)
    const sortBy = ref('name')  // 默认按姓名排序
    const sortOrder = ref('ascending')  // 默认升序排列
    const departments = ref([])
    const licenseTypes = ['A1', 'A2', 'A3', 'B1', 'B2', 'C1', 'C2', 'C3']

    // 验证规则
    const rules = {
      name: [
        { required: true, message: '请输入姓名', trigger: 'blur' },
        { min: 2, max: 20, message: '长度应为2-20个字符', trigger: 'blur' }
      ],
      gender: [
        { required: true, message: '请选择性别', trigger: 'change' }
      ],
      birthDate: [
        { required: true, message: '请选择出生日期', trigger: 'change' }
      ],
      phone: [
        { required: true, message: '请输入手机号', trigger: 'blur' },
        { pattern: /^1[3-9]\d{9}$/, message: '请输入有效的手机号', trigger: 'blur' }
      ],
      idCardNumber: [
        { required: true, message: '请输入身份证号', trigger: 'blur' },
        { pattern: /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/, message: '请输入有效的身份证号', trigger: 'blur' }
      ],
      department: [
        { required: true, message: '请选择部门', trigger: 'change' }
      ],
      licenseNumber: [
        { required: true, message: '请输入驾驶证号', trigger: 'blur' }
      ],
      licenseType: [
        { required: true, message: '请选择驾驶证类型', trigger: 'change' }
      ],
      licenseExpiryDate: [
        { required: true, message: '请选择驾驶证到期日期', trigger: 'change' }
      ],
      status: [
        { required: true, message: '请选择状态', trigger: 'change' }
      ]
    }

    // 计算属性
    const filteredDrivers = computed(() => {
      return drivers.value.map(driver => {
        // 处理状态显示
        if (driver.status !== undefined) {
          driver.statusText = getStatusLabel(driver.status);
          driver.statusType = getStatusType(driver.status);
        } else {
          // 默认为在职状态
          driver.statusText = '在职';
          driver.statusType = 'success';
          driver.status = '1';
        }
        
        return driver;
      });
    })

    // 计算年龄
    const calculateAge = (birthDate) => {
      if (!birthDate) return null;
      const today = new Date();
      const birthDateObj = new Date(birthDate);
      let age = today.getFullYear() - birthDateObj.getFullYear();
      const monthDiff = today.getMonth() - birthDateObj.getMonth();
      if (monthDiff < 0 || (monthDiff === 0 && today.getDate() < birthDateObj.getDate())) {
        age--;
      }
      return age;
    };

    // 方法
    const loadDrivers = async () => {
      loading.value = true
      try {
        // 构造API请求参数
        const params = {
          current: currentPage.value,
          size: pageSize.value,
          searchTerm: searchForm.name || searchForm.phone || null,
          status: searchForm.status || null,
          orderBy: sortBy.value,
          orderType: sortOrder.value
        }
        
        // 调用driverApi的getDriverList方法
        const page = await driverApi.getDriverList(params)
        
        // 解析返回的数据
        if (page && page.records) {
          // 处理每条记录的数据格式
          const processedRecords = page.records.map(driver => {
            // 确保status是字符串
            if (driver.status !== undefined) {
              driver.status = String(driver.status);
            } else {
              driver.status = '1'; // 默认为在职状态
            }
            
            // 确保基本字段不为空
            driver.name = driver.name || '未知姓名';
            driver.gender = driver.gender || '男';
            driver.phone = driver.phone || '未知';
            driver.department = driver.department || '未分配';
            driver.licenseNumber = driver.licenseNumber || '未知';
            
            // 计算年龄
            if (driver.birthDate) {
              driver.age = calculateAge(driver.birthDate);
            } else {
              driver.age = 0;
            }
            
            return driver;
          });
          
          drivers.value = processedRecords;
          totalDrivers.value = page.total || 0;
          console.log('驾驶员数据加载成功:', drivers.value.length, '条记录')
        } else {
          drivers.value = []
          totalDrivers.value = 0
          console.warn('返回的驾驶员数据格式不正确:', page)
        }
      } catch (error) {
        console.error('加载驾驶员数据失败:', error)
        ElMessage.error('加载数据失败，请稍后重试')
      } finally {
        loading.value = false
      }
    }

    const loadDepartments = async () => {
      try {
        const result = await driverApi.getDepartments()
        if (Array.isArray(result)) {
          departments.value = result
        }
      } catch (error) {
        console.error('加载部门失败:', error)
      }
    }

    const handleSearch = () => {
      currentPage.value = 1
      loadDrivers()
    }

    const resetSearch = () => {
      Object.keys(searchForm).forEach(key => {
        searchForm[key] = ''
      })
      handleSearch()
    }

    const handleSortChange = ({ prop, order }) => {
      if (prop) {
        sortBy.value = prop
        sortOrder.value = order
        loadDrivers()
      }
    }

    const handleSizeChange = (size) => {
      pageSize.value = size
      loadDrivers()
    }

    const handleCurrentChange = (page) => {
      currentPage.value = page
      loadDrivers()
    }

    const openDialog = (isEditMode = false) => {
      isEdit.value = isEditMode
      dialogVisible.value = true
      
      if (!isEditMode) {
        // 加载部门数据
        loadDepartments()
        
        // 新增模式，重置表单
        Object.keys(driverForm).forEach(key => {
          if (key === 'status') {
            driverForm[key] = '1'
          } else if (key === 'gender') {
            driverForm[key] = '男'
          } else if (key === 'licenseType') {
            driverForm[key] = 'C1'
          } else if (key !== 'id') {
            driverForm[key] = ''
          }
        })
        
        // 设置默认日期
        const now = new Date()
        driverForm.joinDate = now.toISOString().split('T')[0]
        // 默认驾照到期日期为10年后
        const expiryDate = new Date()
        expiryDate.setFullYear(expiryDate.getFullYear() + 10)
        driverForm.licenseExpiryDate = expiryDate.toISOString().split('T')[0]
      }
    }

    const handleEdit = (row) => {
      // 编辑模式，复制数据到表单
      console.log('编辑的原始数据:', JSON.stringify(row));
      
      // 手动设置每个字段，确保正确获取
      driverForm.id = row.id;
      driverForm.name = row.name || '';
      driverForm.gender = row.gender || '男';
      driverForm.birthDate = row.birthDate || '';
      driverForm.phone = row.phone || '';
      driverForm.idCardNumber = row.idCardNumber || '';
      driverForm.department = row.department || '';
      driverForm.licenseNumber = row.licenseNumber || '';
      driverForm.licenseType = row.licenseType || 'C1';
      driverForm.licenseExpiryDate = row.licenseExpiryDate || '';
      driverForm.status = row.status !== undefined ? String(row.status) : '1';
      driverForm.joinDate = row.joinDate || '';
      driverForm.remark = row.remark || '';
      
      console.log('设置后的表单数据:', JSON.stringify(driverForm));
      
      // 加载部门数据
      loadDepartments();
      
      openDialog(true);
    }

    const handleDelete = (row) => {
      ElMessageBox.confirm(
        `确认删除驾驶员 ${row.name} 的记录吗？`,
        '警告',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).then(async () => {
        try {
          loading.value = true
          // 调用driverApi的deleteDriver方法
          await driverApi.deleteDriver(row.id)
          ElMessage.success('删除成功')
          loadDrivers() // 重新加载列表
        } catch (error) {
          console.error('删除驾驶员失败:', error)
          ElMessage.error('删除失败，请稍后重试')
        } finally {
          loading.value = false
        }
      }).catch(() => {
        // 用户取消删除
      })
    }

    const submitForm = () => {
      formRef.value.validate(async (valid) => {
        if (valid) {
          try {
            loading.value = true
            // 确保表单数据完整性
            if (!driverForm.status) {
              driverForm.status = '1'; // 默认为在职状态
            }
            
            // 处理日期和数据类型
            const dataToSubmit = { ...driverForm };
            console.log('提交前的表单数据:', JSON.stringify(dataToSubmit));
            
            // 确保日期字段使用正确的格式
            ['birthDate', 'licenseExpiryDate', 'joinDate'].forEach(dateField => {
              if (!dataToSubmit[dateField]) {
                dataToSubmit[dateField] = null;
              }
            });
            
            console.log('处理后准备提交的数据:', JSON.stringify(dataToSubmit));
            
            // 调用driverApi添加或更新驾驶员
            if (isEdit.value) {
              await driverApi.updateDriver(dataToSubmit)
              ElMessage.success('更新成功')
            } else {
              await driverApi.addDriver(dataToSubmit)
              ElMessage.success('添加成功')
            }
            dialogVisible.value = false
            loadDrivers() // 重新加载列表
          } catch (error) {
            console.error('提交表单失败:', error)
            ElMessage.error('操作失败，请稍后重试')
          } finally {
            loading.value = false
          }
        }
      })
    }

    const exportData = async () => {
      try {
        loading.value = true
        ElMessage.info('正在导出数据，请稍候...')
        
        // 构建导出参数，使用当前的筛选条件
        const params = {
          searchTerm: searchForm.name || searchForm.phone || null,
          status: searchForm.status || null
        }
        
        console.log('导出参数:', params)
        
        try {
          // 调用API获取导出数据
          const response = await driverApi.exportDrivers(params)
          console.log('导出响应:', response)
          
          // 检查响应是否包含有效数据
          if (!response || !response.data) {
            throw new Error('导出数据为空')
          }
          
          // 检查导出的数据大小
          if (response.data.size === 0) {
            throw new Error('导出数据大小为0，可能没有数据或导出失败')
          }
          
          // 创建Blob对象
          const blob = new Blob([response.data], { 
            type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' 
          })
          
          // 创建下载链接并触发下载
          const link = document.createElement('a')
          const fileName = `drivers_export_${new Date().toISOString().split('T')[0]}.xlsx`
          
          // 创建URL并设置下载属性
          const url = window.URL.createObjectURL(blob)
          link.href = url
          link.download = fileName
          
          // 将链接添加到页面并触发点击
          document.body.appendChild(link)
          link.click()
          
          // 清理
        setTimeout(() => {
            window.URL.revokeObjectURL(url)
            document.body.removeChild(link)
          }, 100)
          
          ElMessage.success('数据导出成功')
        } catch (apiError) {
          console.error('导出API调用失败:', apiError)
          ElMessage.error(`导出失败: ${apiError.message || '未知错误'}`)
          throw apiError
        }
      } catch (error) {
        console.error('导出数据失败:', error)
        ElMessage.error('导出失败，请稍后重试')
      } finally {
        loading.value = false
      }
    }

    const getStatusLabel = (status) => {
      // 确保状态是字符串
      const statusStr = String(status);
      return statusOptions[statusStr] || '未知状态';
    }

    const getStatusType = (status) => {
      // 确保状态是字符串
      const statusStr = String(status);
      const types = {
        '1': 'success',
        '2': 'warning',
        '3': 'danger',
        '4': 'info'
      }
      return types[statusStr] || 'info';
    }

    const toggleMobileMenu = () => {
      // 控制移动端菜单显示
      const event = new CustomEvent('toggle-sidebar')
      window.dispatchEvent(event)
    }

    // 初始化
    onMounted(() => {
      loadDrivers()
      loadDepartments()
    })

    return {
      DEFAULT_PAGE_SIZES,
      statusOptions,
      formRef,
      dialogVisible,
      isEdit,
      driverForm,
      searchForm,
      loading,
      drivers,
      currentPage,
      pageSize,
      totalDrivers,
      filteredDrivers,
      departmentOptions,
      departments,
      licenseTypes,
      rules,
      calculateAge,
      loadDrivers,
      handleSearch,
      resetSearch,
      handleSortChange,
      handleSizeChange,
      handleCurrentChange,
      openDialog,
      handleEdit,
      handleDelete,
      submitForm,
      getStatusLabel,
      getStatusType,
      toggleMobileMenu,
      exportData
    }
  }
}
</script>

<style scoped>
.container {
  padding: 1rem;
  position: relative;
}

.search-container {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
  align-items: center;
}

.search-item {
  flex: 1;
  min-width: 200px;
}

.search-actions {
  display: flex;
  gap: 8px;
  margin-left: auto;
}

.action-buttons {
  display: flex;
  gap: 8px;
}

.mobile-menu-toggle {
  position: absolute;
  top: 10px;
  left: 10px;
  z-index: 10;
}

@media (max-width: 768px) {
  .hide-on-mobile {
    display: none;
  }
  
  .search-item {
    min-width: 100%;
  }
  
  .search-actions {
    width: 100%;
    margin-top: 12px;
    justify-content: center;
  }
}
</style> 